import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException
} from '@nestjs/common';
import { CommonResult } from 'src/common/CommonResult';
import HTTP_STATUS_MSG_MAP from 'src/common/HttpStatusMsgMap';

/**
 * 过滤器
 * 拦截错误请求
 */
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse(); // 获取请求上下文中的 response对象
    const status = exception.getStatus(); // 获取异常状态码

    // 设置返回的状态码， 请求头，发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(
      CommonResult.error(HTTP_STATUS_MSG_MAP[status] || '服务异常，操作失败')
    );
  }
}
